package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.ConsulConfig;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutContract;
import com.lkd.emq.MqttProducer;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.feign.VMService;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.DistributedLock;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
@Topic(TopicConfig.VMS_VENDOUT_TOPIC)
public class OutShopHandle implements MsgHandler {
    @Autowired
    ChannelService channelService;
    @Autowired
    VendoutRunningService vendoutRunningService;
    @Autowired
    MqttProducer mqttProducer;
    @Autowired
    ConsulConfig consulConfig;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("接收订单消息");
        VendoutContract vendoutContract = JsonUtil.getByJson(jsonMsg, VendoutContract.class);
        List<ChannelEntity> lists = channelService.getChannelesByInnerCode(vendoutContract.getInnerCode());
        Optional<ChannelEntity> result = lists.stream()
                .filter(c -> c.getCurrentCapacity() > 0)
                .filter(c -> c.getSkuId().equals(vendoutContract.getVendoutData().getSkuId()))
                .findFirst();
        if (result.isPresent()) {
            ChannelEntity channelEntity = result.get();
            channelEntity.setCurrentCapacity(channelEntity.getCurrentCapacity()-1);
            channelService.updateById(channelEntity);//库存减一
            VendoutRunningEntity vendoutRunningEntity = new VendoutRunningEntity();
            vendoutRunningEntity.setOrderNo(vendoutContract.getVendoutData().getOrderNo());
            vendoutRunningEntity.setInnerCode(vendoutContract.getInnerCode());
            vendoutRunningEntity.setSkuId(channelEntity.getSkuId());
            vendoutRunningEntity.setStatus(false);
            vendoutRunningService.save(vendoutRunningEntity);
            vendoutContract.getVendoutData().setChannelCode(channelEntity.getChannelCode());
            log.info("售货机服务发送给售货机");
            mqttProducer.send(TopicConfig.getVendoutTopic(vendoutContract.getInnerCode()),2,vendoutContract);
            //释放锁
            DistributedLock lock = new DistributedLock(
                    consulConfig.getConsulRegisterHost(),
                    consulConfig.getConsulRegisterPort());
            String sessionId = (String) redisTemplate.boundValueOps(
                    VMSystem.VM_LOCK_KEY_PREF + vendoutContract.getInnerCode()
                            + "_" + vendoutContract.getVendoutData().getSkuId()).get();
            log.info("释放锁：{}",sessionId);
            lock.releaseLock(sessionId);
        }
    }
}
